using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using BulletOnRails4NET.Controllers;
using GeneCMS.Models.physical;
using BulletOnRails4NET.Models;
using Suteki.Common.Repositories;
using BulletOnRailsNET.Models.FormBuilder;
using GeneCMS.Models.View;

namespace GeneCMS.Controllers
{
    [Authorize]
    public class PagesController : GenePublicController//: ScaffoldController<Page>
    {

        #region CRUD_METHODS
        public static string EscapeJS(string str)
        {
            return str.Replace("'", "\\'").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "");
        }

        [AcceptVerbs("GET")]
        public ActionResult List(int id)
        {
            return CreateCrudViewResult(null, "", id);
        }

        private ViewResult CreateCrudViewResult(PageView curr_product, string message, int websiteid)
        {
            if (curr_product == null)
                curr_product = new PageView();
            CrudFormViewModel<PageView> model = new CrudFormViewModel<PageView>();
            var db = new CMSDBDataContext();
            model.List = db.GetPagesForWebsite(websiteid, User.Identity.Name).Select(m => new PageView(m)).ToList();
            //model.List = db.GetAll().Where(a => a.PageID == pageid).Select(m => new PageView(m));
            model.CurrentModel = curr_product;
            model.MetadataType = null;
            model.PropertiesToCrud = typeof(PageView).GetProperties();
            model.StatusMessage = EscapeJS(message);
            model.ParentID = websiteid;
            return View("CRUDForm", model);
        }

        [AcceptVerbs("POST")]
        [ValidateInput(false)]
        public ActionResult Edit(int id, PageView page_updated)
        {
            var db = new Repository<Page>();
            var prodcut = db.GetById(page_updated.ID);
            try
            {
                var sp_executor = new CMSDBDataContext();
                sp_executor.PageUpdate(page_updated.ID, page_updated.Title, page_updated.Position, page_updated.ParentPageID,
                    page_updated.Url, page_updated.Folder, page_updated.WebsiteID, page_updated.InMenu, page_updated.Description,
                    page_updated.Keywords, page_updated.CustomHeadContent, User.Identity.Name);
                return CreateCrudViewResult(page_updated, "Object Saved", id);
            }
            catch (Exception e)
            {

                return CreateCrudViewResult(page_updated, "Error Updating object: " + e.ToString(), id);
            }
        }

        [AcceptVerbs("POST")]
        [ValidateInput(false)]
        public ActionResult Create(int id, PageView page_created)
        {
            var db = new Repository<Page>();
            try
            {
                var sp_executor = new CMSDBDataContext();
                sp_executor.PageInsert(page_created.Title, page_created.Position, page_created.ParentPageID,
                    page_created.Url, page_created.Folder, page_created.WebsiteID, page_created.InMenu, page_created.Description,
                    page_created.Keywords, page_created.CustomHeadContent, User.Identity.Name);
                return CreateCrudViewResult(page_created, "Object Created", id);
            }
            catch (Exception e)
            {
                return CreateCrudViewResult(page_created, "Error Creating object: " + e.ToString(), id);
            }
        }
        [AcceptVerbs("POST")]
        public ActionResult Delete(int id, int DeleteID)
        {
            var db = new Repository<Page>();
            var prodcut = db.GetById(DeleteID);
            try
            {
                if (prodcut == null)
                {
                    return CreateCrudViewResult(null, "Error Deleting object: Object not found with ID " + DeleteID, id);

                }
                else
                {
                    var sp_executor = new CMSDBDataContext();
                    sp_executor.PageDelete(DeleteID, User.Identity.Name);
                    return CreateCrudViewResult(null, "Object Created", id);
                }
            }
            catch (Exception e)
            {
                return CreateCrudViewResult(null, "Error Deleting object: " + e.ToString(), id);
            }
        }
        #endregion



        //    [AcceptVerbs(HttpVerbs.Post)]
        //    public override ActionResult Create(FormCollection formValues)
        //    {
        //        formValues.Add("WebsiteID", GetUserWebsite().WebsiteID.ToString());
        //        return base.Create(formValues);
        //    }
        //    [AcceptVerbs(HttpVerbs.Post)]
        //    public override JsonResult Edit(int id, FormCollection formValues)
        //    {
        //        formValues.Add("WebsiteID", GetUserWebsite().WebsiteID.ToString());
        //        return base.Edit(id, formValues);
        //    }

        //    public override ActionResult EditMultiple(FormCollection formValues)
        //    {
        //        return null;
        //    }

        //    [AcceptVerbs(HttpVerbs.Post)]
        //    public override ActionResult Delete()
        //    {
        //        string ids_to_delete = Request.Form["ids_to_delete"];
        //        string[] ids_to_delete_arr = ids_to_delete.Split(',');
        //        int id;

        //        int website_id = GetUserWebsite().WebsiteID;

        //        List<String> labels_of_records_deleted = new List<String>();
        //        foreach (string str_id in ids_to_delete_arr)
        //        {
        //            if (int.TryParse(str_id, out id))
        //            {
        //                Page model = (Page)_db.GetAll().Where(p => p.ID == id && p.WebsiteID == website_id);
        //                if (model != null)
        //                {
        //                    _db.DeleteOnSubmit(model);
        //                    labels_of_records_deleted.Add(model.GetAsLabel());
        //                }
        //            }
        //        }
        //        _db.SubmitChanges();
        //        return new JsonResult
        //        {
        //            Data = new
        //            {
        //                type = "Batch Results",
        //                deleted_records = labels_of_records_deleted
        //            }
        //        ,
        //            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        //        };
        //    }
        //}
    }
}